/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package espe.ccsoft.controllers;

import espe.ccsoft.controllers.utils.JsfUtil;
import espe.ccsoft.controllers.utils.PaginationHelper;
import espe.ccsoft.dao.RolDao;
import espe.ccsoft.models.Rol;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@ManagedBean
@RequestScoped
public class RolController {

    private Rol rol;
    private DataModel items = null;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private RolDao roldao;
    private List<Integer> id_accionroles;

    public Rol getSelected() {
        if (rol == null) {
            rol = new Rol();
            selectedItemIndex = -1;
        }
        return rol;
    }

    public RolDao getRolDao() {
        roldao = new RolDao();
        return roldao;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    try {
                        return getRolDao().findAll().size();
                    } catch (Exception ex) {
                        return 0;
                    }
                }

                @Override
                public DataModel createPageDataModel() {
                    try {
                        return new ListDataModel(getRolDao().findAll());
                    } catch (Exception ex) {
                        return new ListDataModel();
                    }
                }
            };
        }
        return pagination;
    }

    public final String cargarCrarRol() {
        rol = new Rol();
        selectedItemIndex = -1;
        return "Crear";
    }

    public final String crearRol() throws Exception {
        RolDao dao = new RolDao();

        Rol rolTmp = dao.findByNombre(rol.getNombre());
        try {
            if (rolTmp == null) {
                dao.insert(rol);
                JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Rol").getString("CrearRol"));
                return "Index";
            } else {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Rol").getString("ValidarNombreRol"));
                return null;
            }
        } catch (Exception e) {
            return "/Error";
        }
    }

    public final String cargarEditarRol() {
        rol = (Rol) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Modificar";
    }

    public final String editarRol() throws Exception {
        RolDao dao = new RolDao();

        try {
            if (validarEntradasRol(rol)) {
                AccionRolController accionrol = new AccionRolController();
                id_accionroles = new ArrayList<>();
                HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

                String[] acciones = request.getParameterValues("accionesSeleccionadas");

                for (String accion : acciones) {
                    id_accionroles.add(Integer.parseInt(accion));
                }

                if (id_accionroles != null || !id_accionroles.isEmpty()) {
                    accionrol.elminarAcciones(rol.getId());
                    accionrol.crearAcciones(id_accionroles, rol.getId());
                }
                dao.update(rol);

                JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Rol").getString("EditarRol"));
                return "Index";
            } else {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/Rol").getString("ValidarNombreRol"));
                return null;
            }
        } catch (Exception e) {
            return "/Error";
        }
    }

    public final String cargarDetalleRol() {
        rol = (Rol) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Detalle";
    }

    public final String cargarEditarDetalleRol(int id_rol) throws Exception {
        rol = getRolDao().findByPK(id_rol);
        return "Modificar";
    }

    public final String cargarDetalleEditarRol(int id_rol) throws Exception {
        rol = getRolDao().findByPK(id_rol);
        return "Detalle";
    }

    public final boolean validarEntradasRol(Rol rol) throws Exception {
        RolDao dao = new RolDao();

        Rol rolTmp = dao.findByNombre(rol.getNombre());

        if (rolTmp != null) {
            return rolTmp.getId() == rol.getId();
        } else {
            return true;
        }

    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    public Rol getRolById(int id_rol) throws Exception {
        return getRolDao().findByPK(id_rol);
    }

    public String getNombreRolById() throws Exception {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        int id_rol = (Integer) session.getAttribute("Id_Rol");
        return getRolDao().findByPK(id_rol).getNombre();
    }
    
    public String getNombreRolByUsuario(int id_rol) throws Exception {
        return getRolDao().findByPK(id_rol).getNombre();
    }

    public List<Rol> getRolesDisponibles() throws Exception {
        return getRolDao().findAll();
    }

    public List<Rol> getRolesPermisos(int id_permiso) throws Exception {
        return getRolDao().findAllByPermisos(id_permiso);
    }

    public List<Integer> getId_accionroles() throws Exception {
        return id_accionroles;
    }

    public void setId_accionroles(List<Integer> id_accionroles) {
        this.id_accionroles = id_accionroles;
    }
}
